package com.neusoft.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neusoft.mapper.FollowMapper;
import com.neusoft.mapper.UsersMapper;
import com.neusoft.model.Users;
import com.neusoft.service.IProfileService;
import com.neusoft.utils.UserUtils;
import com.neusoft.vo.Profile;
import com.neusoft.vo.ProfileVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ProfileService implements IProfileService {
    @Autowired
    UsersMapper usersMapper;
    @Autowired
    FollowMapper followMapper;

    @Override
    public ProfileVo getProflie(String username) {
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        Users users = usersMapper.selectOne(wrapper);
        Profile profile = new Profile();
        Users currentUser = UserUtils.getLoginUser();
        boolean isFollow;
        if (currentUser == null) {
            isFollow = followMapper.isFollowing(0, users.getId());
        } else {
            isFollow = followMapper.isFollowing(currentUser.getId(), users.getId());
        }

        profile.setUsername(users.getUsername());
        profile.setBio(users.getBio());
        profile.setImage(users.getImage());
        profile.setFollowing(isFollow);
        ProfileVo profileVo = new ProfileVo();
        profileVo.setProfile(profile);
        return profileVo;
    }

    public ProfileVo follow(String username) {
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        Users users = usersMapper.selectOne(wrapper);
        int followeeId = users.getId();
        Users currentUser = UserUtils.getLoginUser();
        followMapper.addFollow(currentUser.getId(), followeeId);
        return getProflie(username);
    }

    @Override
    public ProfileVo unFollow(String username) {
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        Users users = usersMapper.selectOne(wrapper);
        int followeeId = users.getId();
        Users currentUser = UserUtils.getLoginUser();
        followMapper.deleteFollow(currentUser.getId(), followeeId);
        return getProflie(username);
    }
}
